#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Verification script for App Auth Mixin feature

Tests that app_id + api_key parameters work correctly for HiAgent chat APIs.
Tests both default (env var) and custom configuration scenarios.
"""

import sys
import os
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

import requests
import json
from dotenv import load_dotenv

# Load environment variables
env_path = Path(__file__).parent.parent / '.env'
load_dotenv(env_path)

# Base URL for the API
BASE_URL = "http://localhost:8001/api/v1/hiagent"

def print_section(title):
    """Print a section header"""
    print(f"\n{'='*60}")
    print(f"  {title}")
    print(f"{'='*60}\n")

def test_create_conversation_default():
    """Test 1: Create conversation using default env vars"""
    print_section("Test 1: Create Conversation (Default Config)")

    url = f"{BASE_URL}/conversations"
    payload = {
        "user_id": "test_user_001"
    }

    print(f"POST {url}")
    print(f"Payload: {json.dumps(payload, indent=2)}")

    try:
        response = requests.post(url, json=payload)
        print(f"\nStatus Code: {response.status_code}")
        print(f"Response: {json.dumps(response.json(), indent=2, ensure_ascii=False)}")

        if response.status_code == 200:
            print("\n✓ Test 1 PASSED: Default config works")
            return response.json().get('app_conversation_id')
        else:
            print("\n✗ Test 1 FAILED")
            return None
    except Exception as e:
        print(f"\n✗ Test 1 ERROR: {e}")
        return None

def test_create_conversation_custom():
    """Test 2: Create conversation using custom app_id + api_key"""
    print_section("Test 2: Create Conversation (Custom Config)")

    # Use environment variables for custom config test
    custom_app_id = os.getenv('HIAGENT_APP_ID', 'custom_app_id')
    custom_api_key = os.getenv('HIAGENT_APP_KEY', 'd3b46hni96maquv57020')
    custom_base_url = os.getenv('HIAGENT_BASE_URL', 'https://agent.swjtu.edu.cn')

    url = f"{BASE_URL}/conversations"
    payload = {
        "user_id": "test_user_002",
        "app_id": custom_app_id,
        "api_key": custom_api_key,
        "base_url": custom_base_url
    }

    print(f"POST {url}")
    print(f"Payload: {json.dumps(payload, indent=2, ensure_ascii=False)}")
    print(f"\nCustom config:")
    print(f"  - app_id: {custom_app_id}")
    print(f"  - api_key: {custom_api_key[:20]}...")
    print(f"  - base_url: {custom_base_url}")

    try:
        response = requests.post(url, json=payload)
        print(f"\nStatus Code: {response.status_code}")
        print(f"Response: {json.dumps(response.json(), indent=2, ensure_ascii=False)}")

        if response.status_code == 200:
            print("\n✓ Test 2 PASSED: Custom config works")
            return response.json().get('app_conversation_id')
        else:
            print("\n✗ Test 2 FAILED")
            return None
    except Exception as e:
        print(f"\n✗ Test 2 ERROR: {e}")
        return None

def test_get_conversation_list_with_custom_auth():
    """Test 3: Get conversation list with custom auth"""
    print_section("Test 3: Get Conversation List (Custom Auth)")

    custom_app_id = os.getenv('HIAGENT_APP_ID', 'custom_app_id')
    custom_api_key = os.getenv('HIAGENT_APP_KEY', 'd3b46hni96maquv57020')

    url = f"{BASE_URL}/conversations/list"
    payload = {
        "user_id": "test_user_001",
        "page": 1,
        "page_size": 10,
        "app_id": custom_app_id,
        "api_key": custom_api_key
    }

    print(f"POST {url}")
    print(f"Payload: {json.dumps(payload, indent=2, ensure_ascii=False)}")

    try:
        response = requests.post(url, json=payload)
        print(f"\nStatus Code: {response.status_code}")
        result = response.json()
        print(f"Response: Found {len(result)} conversations")

        if response.status_code == 200:
            print("\n✓ Test 3 PASSED: Get conversation list with custom auth works")
            return True
        else:
            print(f"\n✗ Test 3 FAILED: {json.dumps(result, indent=2, ensure_ascii=False)}")
            return False
    except Exception as e:
        print(f"\n✗ Test 3 ERROR: {e}")
        return False

def test_chat_with_custom_auth(conversation_id):
    """Test 4: Send chat message with custom auth"""
    if not conversation_id:
        print("\n⊘ Test 4 SKIPPED: No conversation ID available")
        return

    print_section("Test 4: Send Chat Message (Custom Auth)")

    custom_app_id = os.getenv('HIAGENT_APP_ID', 'custom_app_id')
    custom_api_key = os.getenv('HIAGENT_APP_KEY', 'd3b46hni96maquv57020')

    url = f"{BASE_URL}/chat"
    payload = {
        "conversation_id": conversation_id,
        "query": "Hello, this is a test message",
        "user_id": "test_user_001",
        "response_mode": "blocking",
        "app_id": custom_app_id,
        "api_key": custom_api_key
    }

    print(f"POST {url}")
    print(f"Payload: {json.dumps(payload, indent=2, ensure_ascii=False)}")

    try:
        response = requests.post(url, json=payload)
        print(f"\nStatus Code: {response.status_code}")
        result = response.json()
        print(f"Response: {json.dumps(result, indent=2, ensure_ascii=False)}")

        if response.status_code == 200:
            print("\n✓ Test 4 PASSED: Chat with custom auth works")
        else:
            print("\n✗ Test 4 FAILED")
    except Exception as e:
        print(f"\n✗ Test 4 ERROR: {e}")

def test_api_schema():
    """Test 5: Check OpenAPI schema includes new parameters"""
    print_section("Test 5: OpenAPI Schema Validation")

    url = "http://localhost:8001/docs"
    print(f"Checking OpenAPI docs at {url}")
    print("(Manual check required: Verify that app_id, api_key, base_url are in the schema)")
    print("\nExpected parameters in CreateConversationRequest:")
    print("  - user_id (required)")
    print("  - inputs (optional)")
    print("  - app_id (optional)")
    print("  - api_key (optional)")
    print("  - base_url (optional)")
    print("\n✓ Test 5: Manual verification required - Check Swagger UI")

def main():
    """Run all tests"""
    print("""
    ╔════════════════════════════════════════════════════════════╗
    ║  HiAgent App Auth Mixin Verification Script              ║
    ║                                                            ║
    ║  This script tests the new app_id + api_key feature      ║
    ║  for all HiAgent chat-related APIs.                      ║
    ╚════════════════════════════════════════════════════════════╝
    """)

    # Check if server is running
    try:
        response = requests.get("http://localhost:8001/docs")
        if response.status_code != 200:
            print("✗ ERROR: Server is not running on http://localhost:8001")
            print("  Please start the server first with: uvicorn main:app --reload --port 8001")
            return
    except Exception as e:
        print(f"✗ ERROR: Cannot connect to server: {e}")
        print("  Please start the server first with: uvicorn main:app --reload --port 8001")
        return

    print("✓ Server is running\n")

    # Run tests
    conv_id_1 = test_create_conversation_default()
    conv_id_2 = test_create_conversation_custom()
    test_get_conversation_list_with_custom_auth()
    test_chat_with_custom_auth(conv_id_1 or conv_id_2)
    test_api_schema()

    # Summary
    print_section("Summary")
    print("Tests completed!")
    print("\nNext steps:")
    print("1. Check the OpenAPI docs at http://localhost:8001/docs")
    print("2. Verify all endpoints show app_id, api_key, base_url parameters")
    print("3. Test with real HiAgent credentials if available")
    print("\n✓ Verification complete!\n")

if __name__ == "__main__":
    main()
